<template>
     <div class="register">
    <div class="container">
      <div class="row">
        <div class="col-md-8 m-auto">
          <h1 class="display-4 text-center">注册</h1>
          <p class="lead text-center">创建新的账户</p>
          <!--  prevent 阻止我们的默认事件 autocomplete：0ff不会记录我们之前写的东西-->
          <form @submit.prevent="submit" autocomplete="off"> 
            <TextField 
                type='text' 
                name='name' 
                placeholder="用户名"
                v-model="newUser.name"
                :error = "errors.name"
            />
            <TextField 
                type='email' 
                name='email' 
                placeholder="邮箱地址"
                v-model="newUser.email"
                :error="errors.email"
                info = "我们使用了gravatar全球公认的头像，如果需要有头像显示，请使用gravatar注册邮箱"
            />
            <TextField 
                type='password' 
                name='password' 
                placeholder="密码"
                v-model="newUser.password"
                :error="errors.password"
            />
            <TextField 
                type='password' 
                name='password2' 
                placeholder="确认密码"
                v-model="newUser.password2"
                :error="errors.password2"
            />
              <input type="submit"  class="btn btn-info btn-block mt-4" />
          </form>
        </div> 
      </div>
    </div>
  </div>
</template>

<script>
import TextField from './common/TextFieldGroup'
    export default {
        name:"Register",
        data(){
            return {
                newUser:{
                    name:"",
                    email:"",
                    password:"",
                    password2:""
                },
                errors:{}
            };
        },
        components:{
            TextField
        },
        methods:{
            submit(){
                console.log(this.$store.getters.isAuthenticated)
                this.$axios.post("/api/users/register",this.newUser)
                           .then(res =>{
                            this.errors = ""; // 清空页面错误信息
                            // 执行mutation操作
                            // this.$store.commit("setUser",res.data);
                            // 执行action异步操作
                            this.$store.dispatch("setUser",res.data);
                            // 进行页面跳转
                            this.$router.push("/login");
                           })
                           .catch(err =>{
                               if (err.response.data) {
                                  this.errors = err.response.data.errors  || err.response.data
                               }              
                           })
            }
        }
    }
</script>

<style scoped>

</style>